package cn.backflow.admin.service;

import cn.backflow.admin.Constants;
import cn.backflow.admin.entity.User;
import cn.backflow.web.SpringContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.Map;
import java.util.Set;

import static cn.backflow.admin.Constants.SESSION_PERMISSIONS_KEY;

/**
 * Redis sysCache service
 * Created by Nandy on 2016/5/9.
 */
public abstract class CacheService {
    private static final Logger logger = LoggerFactory.getLogger(CacheService.class);

    private static final String KEY_SEPARATOR = "_";

    private static CacheManager cacheManager = SpringContexts.getBean(CacheManager.class);
    private static Cache permCache; // 缓存权限相关
    private static Cache sysCache;  // 系统通用缓存

    static {
        logger.info("Avalible cache names are: " + cacheManager.getCacheNames());
        permCache = cacheManager.getCache(Constants.PERMISSION_CACHE);
        sysCache = cacheManager.getCache(Constants.SYSTEM_CACHE);
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Integer> get(String key) {
        return sysCache.get(key, Map.class);
    }

    public static void put(String key, Object val) {
        sysCache.put(key, val);
    }

    @SuppressWarnings("unchecked")
    public static Set<String> getUserPermissions(User user) {
        return permCache.get(keyFor(SESSION_PERMISSIONS_KEY, user.getId()), Set.class);
    }

    public static void storeUserPermission(Set<String> permissions, User user) {

        permCache.put(keyFor(SESSION_PERMISSIONS_KEY, user.getId()), permissions);
    }

    public static void cleanUserCaches(User user) {
        permCache.evict(keyFor(SESSION_PERMISSIONS_KEY, user.getId()));
    }

    private static String keyFor(String prefix, Object identity) {
        return prefix + KEY_SEPARATOR + identity;
    }
}
